import { UserRole } from '../types/prisma-types';
import { 
  Permission,
  PermissionAction,
  ResourceType,
  checkPermission,
  validateResourceAccess
} from '../types/permissions';
import { Request } from 'express';
import { AuthenticatedRequest } from '../types/auth';

export interface ResourcePermissionConfig {
  resource: ResourceType;
  actions: PermissionAction[];
  ownershipCheck?: boolean;
  ownerIdPath?: string; // 例如: 'params.userId' 或 'body.authorId'
}

export interface RoutePermissionConfig {
  roles?: UserRole[];
  permissions?: ResourcePermissionConfig[];
}

export function getValueFromPath(obj: any, path: string): any {
  return path.split('.').reduce((acc, part) => acc && acc[part], obj);
}

export function checkRoutePermissions(config: RoutePermissionConfig) {
  return async (req: AuthenticatedRequest): Promise<boolean> => {
    if (!req.user) {
      return false;
    }

    // 检查角色权限
    if (config.roles && !config.roles.includes(req.user.role)) {
      return false;
    }

    // 检查资源权限
    if (config.permissions) {
      for (const permConfig of config.permissions) {
        for (const action of permConfig.actions) {
          // 基础权限检查
          if (!checkPermission(req.user.role, action, permConfig.resource)) {
            return false;
          }

          // 所有权检查
          if (permConfig.ownershipCheck && permConfig.ownerIdPath) {
            const resourceOwnerId = getValueFromPath(req, permConfig.ownerIdPath);
            if (!validateResourceAccess(req.user.role, action, permConfig.resource, req.user.id === resourceOwnerId)) {
              return false;
            }
          }
        }
      }
    }

    return true;
  };
}

export function createPermissionChecker(resource: ResourceType) {
  return {
    canCreate: (role: UserRole) => checkPermission(role, 'create', resource),
    canRead: (role: UserRole) => checkPermission(role, 'read', resource),
    canUpdate: (role: UserRole) => checkPermission(role, 'update', resource),
    canDelete: (role: UserRole) => checkPermission(role, 'delete', resource),
    canManage: (role: UserRole) => checkPermission(role, 'manage', resource),
    
    validateAccess: (role: UserRole, action: PermissionAction, isOwner: boolean) => 
      validateResourceAccess(role, action, resource, isOwner)
  };
}

// 用于前端权限检查的辅助函数
export function createClientPermissionChecker(userRole: UserRole) {
  return {
    forResource: (resource: ResourceType) => ({
      canCreate: () => checkPermission(userRole, 'create', resource),
      canRead: () => checkPermission(userRole, 'read', resource),
      canUpdate: () => checkPermission(userRole, 'update', resource),
      canDelete: () => checkPermission(userRole, 'delete', resource),
      canManage: () => checkPermission(userRole, 'manage', resource),
      validateAccess: (action: PermissionAction, isOwner: boolean) => 
        validateResourceAccess(userRole, action, resource, isOwner)
    }),
    
    hasRole: (role: UserRole) => userRole === role,
    isAdmin: () => userRole === UserRole.ADMIN,
    isTeacher: () => userRole === UserRole.TEACHER,
    isStudent: () => userRole === UserRole.STUDENT
  };
}

// 预定义的常用权限配置
export const CommonPermissions = {
  UserManagement: {
    resource: 'user' as ResourceType,
    actions: ['create', 'read', 'update', 'delete', 'manage'] as PermissionAction[]
  },
  QuestionManagement: {
    resource: 'question' as ResourceType,
    actions: ['create', 'read', 'update', 'delete'] as PermissionAction[]
  },
  SubmissionManagement: {
    resource: 'submission' as ResourceType,
    actions: ['create', 'read', 'update'] as PermissionAction[]
  },
  Analytics: {
    resource: 'analytics' as ResourceType,
    actions: ['read'] as PermissionAction[]
  }
};
